package com.nic.view.widget;

import android.content.Context;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;


import com.nic.view.R;
import com.nic.view.adapter.GridChooseDialog;
import com.nic.view.util.DateTimeUtil;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * 时间段选择弹出框
 * Created by Administrator on 2019/4/11.
 */

public class TimeQueryPopupWindow extends CommonPopupWindow implements View.OnClickListener {

    private TextView tv_entrustBeginTime, tv_entrustEndTime;    //开始时间，结束时间
    private TextView tv_cleanTime;//清楚时间
//    private Button btn_entrustBeginTime, btn_entrustEndTime;  //开始时间，结束时间点击按钮

    private CheckBox ck_year, ck_month, ck_day;//选项  年  月 日
    private TextView tv_year, tv_month, tv_day;//文本 年  月  日

    private Context mContext;
    private Button confirm;//提交按钮
    private Button cancel;//取消

    private GridChooseDialog Ydialog;//年的数量
    private GridChooseDialog Mdialog;//月的数量
    private GridChooseDialog Ddialog;//日的数量

    private TextView tv_result;//时间展示结果
    private TextView tv_out;

    //日历提示显示话框
    private CalendarViewDialog calendarViewDialog;

    public TimeQueryPopupWindow(Context c) {
        super(c, R.layout.pop_time_query, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        mContext = context;
        tv_out = (TextView) contentView.findViewById(R.id.tv_out);
        tv_out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPopupWindow().dismiss();
            }
        });
        ck_year = (CheckBox) contentView.findViewById(R.id.ck_year);
        ck_month = (CheckBox) contentView.findViewById(R.id.ck_month);
        ck_day = (CheckBox) contentView.findViewById(R.id.ck_day);
        tv_year = (TextView) contentView.findViewById(R.id.tv_year);
        tv_month = (TextView) contentView.findViewById(R.id.tv_month);
        tv_day = (TextView) contentView.findViewById(R.id.tv_day);
        tv_entrustBeginTime = (TextView) contentView.findViewById(R.id.tv_entrustBeginTime);
        tv_entrustEndTime = (TextView) contentView.findViewById(R.id.tv_entrustEndTime);
        tv_entrustBeginTime.setOnClickListener(this);
        tv_entrustEndTime.setOnClickListener(this);
        tv_cleanTime = (TextView) contentView.findViewById(R.id.tv_cleanTime);
        tv_result = (TextView) contentView.findViewById(R.id.tv_result);
        confirm = (Button) contentView.findViewById(R.id.confirm);
        cancel = (Button) contentView.findViewById(R.id.cancel);
        tv_cleanTime.setOnClickListener(this);
        confirm.setOnClickListener(this);
        cancel.setOnClickListener(this);
        ck_year.setOnClickListener(this);
        ck_month.setOnClickListener(this);
        ck_day.setOnClickListener(this);
        tv_year.setOnClickListener(this);
        tv_month.setOnClickListener(this);
        tv_day.setOnClickListener(this);
        Ydialog = new GridChooseDialog(context);//年
        Mdialog = new GridChooseDialog(context);//月
        Ddialog = new GridChooseDialog(context);//日
    }


    /**
     * 点击事件
     */
    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.tv_entrustBeginTime) {
            if (calendarViewDialog == null) {
                calendarViewDialog = new CalendarViewDialog(mContext, CalendarViewDialog.CORRECT_TO_DAY_1ST);
            }
            calendarViewDialog.setOnBtnClickListener(new CalendarViewDialog.OnBtnClickListener() {
                @Override
                public void onClick(View v) {
                    exclusion(1);
                    tv_entrustBeginTime.setText(calendarViewDialog.getCalendarDate("yyyy-MM-dd"));
                }
            });
            if (!calendarViewDialog.isShowing()) {
                calendarViewDialog.show();
            }

        } else if (i == R.id.tv_entrustEndTime) {
            if (calendarViewDialog == null) {
                calendarViewDialog = new CalendarViewDialog(mContext, CalendarViewDialog.CORRECT_TO_DAY_1ST);
            }
            calendarViewDialog
                    .setOnBtnClickListener(new CalendarViewDialog.OnBtnClickListener() {
                        @Override
                        public void onClick(View v) {
                            exclusion(1);
                            tv_entrustEndTime.setText(calendarViewDialog.getCalendarDate("yyyy-MM-dd"));
                        }
                    });
            if (!calendarViewDialog.isShowing()) {
                calendarViewDialog.show();
            }

        } else if (i == R.id.tv_cleanTime) {// 置空单选
            tv_entrustBeginTime.setText("");
            tv_entrustEndTime.setText("");
            //     checkOnly(null);
            //     tv_year.setText("");
            //     tv_month.setText("");
            //     tv_day.setText("");

        } else if (i == R.id.confirm) {
            getPopupWindow().dismiss();
            //                if (getBeginTime().equals("") || getEndTime().equals("")) {
//                    Toast.makeText(mContext, "时间选择有误，请检查！", Toast.LENGTH_LONG).show();
//                    return;
//                }
            if (!TextUtils.isEmpty(getBeginTime()) && !TextUtils.isEmpty(getEndTime())) {
                String[] st = getBeginTime().split("-");
                String[] nd = getEndTime().split("-");
                if (Integer.parseInt(st[0]) > Integer.parseInt(nd[0])) {
                    Toast.makeText(mContext, "开始年份不能大于结束年份", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (Integer.parseInt(st[0]) == Integer.parseInt(nd[0]) && Integer.parseInt(st[1]) > Integer.parseInt(nd[1])) {
                    Toast.makeText(mContext, "开始月份不能大于结束月份", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (Integer.parseInt(st[0]) == Integer.parseInt(nd[0]) && Integer.parseInt(st[1]) == Integer.parseInt(nd[1]) && Integer.parseInt(st[2]) > Integer.parseInt(nd[2])) {
                    Toast.makeText(mContext, "开始日期不能大于结束日期", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            if (mTimeQueryListener != null) {
                mTimeQueryListener.onClick(v);
            }

        } else if (i == R.id.cancel) {
            getPopupWindow().dismiss();

        } else if (i == R.id.ck_year) {
            checkYear();
            setResultTime();

        } else if (i == R.id.ck_month) {
            checkMonth();
            setResultTime();

        } else if (i == R.id.ck_day) {
            chekDay();
            setResultTime();

        } else if (i == R.id.tv_year) {
            setYearData();
            Ydialog.setTitle("年份选择");
            Ydialog.setGridChooseDialogListener(new GridChooseDialog.OnGridChooseDialogListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String bean = (String) parent.getItemAtPosition(position);
                    if (TextUtils.isEmpty(bean)) {
                        return;
                    }
                    Ydialog.dismiss();
                    exclusion(0);
                    tv_year.setText(bean);
                    ck_year.setChecked(false);
                    ck_month.setChecked(false);
                    ck_day.setChecked(false);
                    tv_day.setText("");
                    setResultTime();
                }

                @Override
                public void onClick(View v) {
                    Ydialog.dismiss();
                    tv_year.setText("");
                    ck_year.setChecked(false);
                    ck_month.setChecked(false);
                    tv_month.setText("");
                    ck_day.setChecked(false);
                    tv_day.setText("");
                    setResultTime();
                }
            });
            Ydialog.show();

        } else if (i == R.id.tv_month) {
            String text = tv_year.getText().toString().trim();
            if (TextUtils.isEmpty(text)) {
                return;
            }
            setMonthData();
            Mdialog.setTitle("月份选择");
            Mdialog.setGridChooseDialogListener(new GridChooseDialog.OnGridChooseDialogListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String bean = (String) parent.getItemAtPosition(position);

                    if (TextUtils.isEmpty(bean)) {
                        return;
                    }
                    Mdialog.dismiss();
                    exclusion(0);
                    tv_month.setText(bean);
                    ck_year.setChecked(false);
                    ck_month.setChecked(false);
                    ck_day.setChecked(false);
                    tv_day.setText("");
                    setResultTime();
                }

                @Override
                public void onClick(View v) {
                    Mdialog.dismiss();
                    tv_month.setText("");
                    ck_month.setChecked(false);
                    ck_day.setChecked(false);
                    tv_day.setText("");
                    setResultTime();
                }
            });
            Mdialog.show();

        } else if (i == R.id.tv_day) {
            String m = tv_month.getText().toString().trim();
            if (TextUtils.isEmpty(m)) {
                return;
            }
            if (tv_year.getText().toString().equals("")) {
                Toast.makeText(mContext, "请先选择年份", Toast.LENGTH_SHORT).show();
                return;
            }
            if (tv_month.getText().toString().equals("")) {
                Toast.makeText(mContext, "请先选择月份", Toast.LENGTH_SHORT).show();
                return;
            }
            setDaysData(Integer.parseInt(tv_year.getText().toString()), Integer.parseInt(tv_month.getText().toString()));
            Ddialog.setTitle("日期选择");
            Ddialog.setGridChooseDialogListener(new GridChooseDialog.OnGridChooseDialogListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String bean = (String) parent.getItemAtPosition(position);
                    if (TextUtils.isEmpty(bean)) {
                        return;
                    }
                    Ddialog.dismiss();
                    exclusion(0);
                    tv_day.setText(bean);
                    ck_year.setChecked(false);
                    ck_month.setChecked(false);
                    ck_day.setChecked(false);
                    setResultTime();
                }

                @Override
                public void onClick(View v) {
                    Ddialog.dismiss();
                    tv_day.setText("");
                    ck_day.setChecked(false);
                    setResultTime();
                }
            });
            Ddialog.show();

        }
    }

    /**
     * 单选操作
     *
     * @param ck
     */
    private void checkOnly(CheckBox ck) {
        ck_year.setChecked(false);
        ck_month.setChecked(false);
        ck_day.setChecked(false);
        if (ck != null) {
            ck.setChecked(true);
        }
    }

    /**
     * 互斥选择
     *
     * @param type 0选择日期  1自定义选择
     */
    private void exclusion(int type) {
        if (type == 0) {//0选择日期
            tv_entrustBeginTime.setText("");
            tv_entrustEndTime.setText("");
        } else if (type == 1) {//1自定义选择
            ck_year.setChecked(false);
            ck_month.setChecked(false);
            ck_day.setChecked(false);
            tv_year.setText("");
            tv_month.setText("");
            tv_day.setText("");
            tv_result.setText("");
        }
    }

    /**
     * 设置年的集合数据
     */
    private void setYearData() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        List<String> data = new ArrayList<>();
        for (int i = 9; i >= 0; i--) {
            data.add((currentYear - i) + "");
        }
        for (int i = 1; i <= 2; i++) {
            data.add((currentYear + i) + "");
        }
        Ydialog.setData(data);
    }

    /**
     * 设置月的结合数据
     */
    private void setMonthData() {
        List<String> data = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            if (1 <= i && i <= 9) {
                data.add("0" + i + "");
            } else {
                data.add(i + "");
            }
        }
        Mdialog.setData(data);
    }

    /**
     * 设置日的集合数据
     */
    private void setDaysData(int year, int month) {
        int days = this.getMonthDays(year, month);
        List<String> data = new ArrayList<>();
        for (int i = 1; i <= days; i++) {
            if (1 <= i && i <= 9) {
                data.add("0" + i + "");
            } else {
                data.add(i + "");
            }

        }
        Ddialog.setData(data);
    }


    private TimeQueryListener mTimeQueryListener;

    public interface TimeQueryListener {
        void onClick(View v);
    }

    public void setTimeQueryListener(TimeQueryListener mTimeQueryListener) {
        this.mTimeQueryListener = mTimeQueryListener;
    }

    /***
     * 获取开始时间
     *
     * @return
     */
    public String getBeginTime() {
        String year = tv_year.getText().toString();
        String month = tv_month.getText().toString();
        String day = tv_day.getText().toString();
        String start = tv_entrustBeginTime.getText().toString();
        if (!year.equals("") && month.equals("") && day.equals("")) {//年
            return DateTimeUtil.getYearFirst(Integer.parseInt(year), "yyyy-MM-dd");
        }
        if (!year.equals("") && !month.equals("") && day.equals("")) {//年月
            return year + "-" + month + "-" + "01";
        }
        if (!year.equals("") && !month.equals("") & !day.equals("")) {//年月日
            return year + "-" + month + "-" + day;
        }
        if (!start.equals("")) {//自定义
            return start;
        }
        return "";
    }

    public String getEndTime() {
        String year = tv_year.getText().toString();
        String month = tv_month.getText().toString();
        String day = tv_day.getText().toString();
        String end = tv_entrustEndTime.getText().toString();
        if (!year.equals("") && month.equals("") && day.equals("")) {//年
            return DateTimeUtil.getYearLast(Integer.parseInt(year), "yyyy-MM-dd");
        }
        if (!year.equals("") && !month.equals("") && day.equals("")) {//年月
            return year + "-" + month + "-" + getMonthDays(Integer.parseInt(year), Integer.parseInt(month));
        }
        if (!year.equals("") && !month.equals("") & !day.equals("")) {//年月日
            return year + "-" + month + "-" + day;
        }
        if (!end.equals("")) {//自定义
            return end;
        }
        return "";
    }

    private void setResultTime() {
        if (!TextUtils.isEmpty(getBeginTime()) && !TextUtils.isEmpty(getEndTime())) {
            tv_result.setText((getBeginTime() + "  至  " + getEndTime()).replace("-", "/"));
        } else {
            tv_result.setText("");
        }
    }

    /**
     * 根据年和月返回当月的天数
     *
     * @param year
     * @param month
     * @return
     */
    private int getMonthDays(int year, int month) {
        switch (month) {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return 31;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            case 2:
                if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
                    return 29;
                } else {
                    return 28;
                }
            default:
                return -1;
        }
    }

    /**
     * 选中本年
     */
    public void checkYear() {
        checkOnly(ck_year);//单项选择
        exclusion(0);//互斥选择
        //  tv_entrustBeginTime.setText(DateUtil.getCurrYearFirst("yyyy-MM-dd"));
        //   tv_entrustEndTime.setText(DateUtil.getCurrYearLast("yyyy-MM-dd"));
        tv_year.setText(DateTimeUtil.getCurrYearFirst("yyyy-MM-dd").split("-")[0]);//设置年
        tv_month.setText("");//设置月
        tv_day.setText("");//设置天
    }

    /**
     * 选中本月
     */
    public void checkMonth() {
        checkOnly(ck_month);//单项选择
        exclusion(0);//互斥选择
        //    tv_entrustBeginTime.setText(DateUtil.getDayOfMonthFirstDay());
        //   tv_entrustEndTime.setText(DateUtil.getDayOfMonthLastDaya());
        tv_year.setText(DateTimeUtil.getDayOfMonthFirstDay().split("-")[0]);//设置年
        tv_month.setText(DateTimeUtil.getDayOfMonthFirstDay().split("-")[1]);//设置月
        tv_day.setText("");//设置日
    }

    /**
     * 选中本日
     */
    public void chekDay() {
        checkOnly(ck_day);//单项选择
        exclusion(0);//互斥选择
        String date = DateTimeUtil.getSystemDate(DateTimeUtil.getSystemDataTime("yyyy-MM-dd"));//获取当期时间
        //  tv_entrustBeginTime.setText(date);
        //   tv_entrustEndTime.setText(date);
        tv_year.setText(date.split("-")[0]);//选择年
        tv_month.setText(date.split("-")[1]);//选择月
        tv_day.setText(date.split("-")[2]);//选择日
    }


}
